import Tools from './tools.js'
//创建食物对象
class Food {
  sub = new Set() //存储添加的食物
  constructor(x, y, width, height, color, position) {
    this.x = x || 0
    this.y = y || 0
    this.width = width || 20
    this.height = height || 20
    this.color = color || 'blue'
    this.position = position || 'absolute'
  }
  render(parent) {
    //创建一个div元素
    var el = document.createElement('div')
    el.style.width = this.width + 'px'
    el.style.height = this.height + 'px'
    el.style.position = this.position
    //设置元素的位置
    this.x =
      Tools.getRandom(0, parent.clientWidth / this.width - 1) * this.width
    this.y =
      Tools.getRandom(0, parent.clientHeight / this.height - 1) * this.height
    el.style.left = this.x + 'px'
    el.style.top = this.y + 'px'
    el.style.backgroundColor = this.color
    //将元素添加到页面中
    parent.appendChild(el)
    this.addSub(el)
  }
  addSub(el) {
    //收集所有食物
    this.sub.add(el)
  }
  deleteSub(el, parent) {
    //删除食物
    this.sub.delete(el)
    parent.removeChild(el)
  }
}

export default Food
